# config/configure.py
import configparser
import logging
import os
import threading
from pathlib import Path

"""
根据传入的device_type，调用不同产品的config.ini配置文件

"""

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class Config:
    _instances = {}  # 改为实例缓存字典
    _lock = threading.Lock()

    def __new__(cls, device_type=None):
        # 标准化设备类型名称
        device_type = cls._normalize_device_type(device_type)

        with cls._lock:
            if device_type not in cls._instances:
                instance = super().__new__(cls)
                instance._initialized = False
                cls._instances[device_type] = instance
            return cls._instances[device_type]

    def __init__(self, device_type=None):
        """初始化方法现在每次都会执行"""
        if not self._initialized:
            # 获取有效的设备类型
            self.device_type = self._get_valid_device_type(device_type)
            self._load_config()
            self._initialized = True

    @classmethod
    def _normalize_device_type(cls, device_type):
        """标准化设备类型名称"""
        if device_type is None:
            device_type = os.getenv("DEVICE_TYPE", "S01")
        return device_type.upper().strip()

    def _get_valid_device_type(self, device_type):
        """验证并返回有效的设备类型"""
        normalized = self._normalize_device_type(device_type)

        return normalized

    def _load_config(self):
        """加载配置文件的核心方法"""
        base_dir = Path(__file__).parent.parent
        self.config_file = base_dir / 'config' / f"config_{self.device_type}" / "config.ini"
        print("self.config_file=", self.config_file)

        if not self.config_file.exists():
            raise FileNotFoundError(f"设备 {self.device_type} 配置文件不存在: {self.config_file}")

        self.config = configparser.ConfigParser()
        self.config.read(self.config_file)
        logger.info(f"成功加载 {self.device_type} 设备配置")

    @property
    def browser_name(self):
        return self.config['Browser'].get('browser_name', 'browser_name')
    @property
    def implicit_wait(self):
        return self.config['Browser'].get('implicit_wait', 'implicit_wait')

    @property
    def base_url(self):
        return self.config['Environment'].get('base_url', 'http://localhost')

    @property
    def base_ip_o(self):
        return self.config['Environment'].get('base_ip_o', '10.4.0.204')

    @property
    def headless(self):
        return self.config['Browser'].get('headless', 'False')

    @property
    def chrome_driver_path(self):
        return self.config['Browser'].get('chrome_driver_path', 'chrome_driver_path')

    @property
    def chrome_binary_path(self):
        return self.config['Browser'].get('chrome_binary_path', 'chrome_binary_path')

    # @property
    # def firefox_driver_path(self):
    #     return self.config['Browser'].get('firefox_driver_path', 'firefox_driver_path')
    #
    # @property
    # def firefox_binary_path(self):
    #     return self.config['Browser'].get('firefox_binary_path', 'firefox_binary_path')

    @property
    def download_dir(self):
        return self.config['Browser'].get('download_dir', '/home/fgl/Downloads/')

    @property
    def username_admin(self):
        return self.config['Environment'].get('username_admin', 'admin')

    @property
    def username_suadmin(self):
        return self.config['Environment'].get('username_suadmin', 'suadmin')

    @property
    def username_audit(self):
        return self.config['Environment'].get('username_audit', 'audit')

    @property
    def password(self):
        return self.config['Environment'].get('password', 'password')

    @property
    def log_path(self):
        return self.config['Logging'].get('log_path', '/default/log/path')

    @property
    def log_level(self):
        return self.config['Logging'].get('log_level', 'INFO').upper()

    @property
    def enable_console_logging(self):
        return self.config['Logging'].getboolean('enable_console_logging', False)

    @property
    def enable_log_rotation(self):
        return self.config['Logging'].getboolean('enable_log_rotation', False)

    @property
    def log_max_bytes(self):
        return self.config['Logging'].getint('log_max_bytes', 10 * 1024 * 1024)  # 默认10MB

    @property
    def log_backup_count(self):
        return self.config['Logging'].getint('log_backup_count', 5)  # 默认保留5个备份

    # 验证码是否开启
    @property
    def captcha_enabled(self):
        return self.config['Captcha'].getboolean('enable_captcha', False)

    @property
    def captcha_retry(self):
        return self.config['Captcha'].getint('retry_times', 3)


def get_config(device_type=None):
    """获取配置实例（支持动态设备类型）"""
    return Config(device_type=device_type)


# 示例使用配置项
if __name__ == "__main__":
    print(f"Browser: {get_config('NATAS').log_level}")
    print(f"Browser: {get_config('NATAS').enable_console_logging}")
    # print(f"Base URL: {config.base_url}")
    # print(f"username: {config.username}")
    # print(f"password: {config.password}")
    # print(f"Log Path: {config.log_path}")
    # print(f"Log Level: {config.log_level}")
    # print(f"Enable Console Logging: {config.enable_console_logging}")
    # print(f"Enable Log Rotation: {config.enable_log_rotation}")
    # print(f"Log Max Bytes: {config.log_max_bytes}")
    # print(f"Log Backup Count: {config.log_backup_count}")